import { OnInit, Component, Output, EventEmitter, ViewChild } from '@angular/core';
import { OperationNotification, OperationType } from 'src/app/project/model/common/operation-notification';
import { NzMessageService } from 'ng-zorro-antd';
import { StudentService } from 'src/app/project/service/icm/icm-system-user/student/student.service';
import { FormBuilder, Validators, NgForm, FormGroup, FormControl, ValidationErrors } from '@angular/forms';
import { StudentDTO } from 'src/app/project/model/icm/icm-system-user/student/student.dto';
import { QueryOptions } from 'src/app/project/model/common/query-options';
import { Observable, Observer, timer } from 'rxjs';
import { FormUtil } from '@shared/utils/form-util';
import { format } from 'date-fns';
import { StudentDetailDTO } from 'src/app/project/model/icm/icm-system-user/student/student-detail.dto';
import { ConfigurationService } from 'src/app/project/service/icm/icm-global/configuration/configuration.service';

@Component({
  selector: 'app-student-detail',
  templateUrl: './student-detail.component.html',
  styles: [],
})
export class StudentDetailComponent implements OnInit {
  constructor(
    private msg: NzMessageService,
    private studentService: StudentService,
    private fb: FormBuilder,
    private configurationService: ConfigurationService,
  ) {
    this.validateForm = this.fb.group({
      code: ['', [Validators.required, Validators.pattern('[\\d]+')], [this.codeAsyncValidator]],
      name: ['', [Validators.required, Validators.pattern('[^ ]+')]],
      grade: ['', [Validators.required]],
      gender: ['', [Validators.required]],
      politicStatus: [''],
      phone: [''],
      idCard: [''],
      familyName: [''],
      familyPhone: [''],
      birthDate: [''],
      joinTime: ['', [Validators.required]],
      studyYears: [1, [Validators.required]],
      isClassEvaluationAdmin: [false, [Validators.required]],
    });
  }

  /**
   * 数据变化通知事件
   */
  @Output()
  notification = new EventEmitter<OperationNotification<StudentDTO>>();

  /**
   * form组件
   */
  @ViewChild('myForm', { static: false })
  public myForm: NgForm;

  /**
   * 表单
   */
  validateForm: FormGroup;

  /**
   * 是否预览
   */
  isPreView = false;

  /**
   * 表单窗体打开/关闭控制
   */
  isVisible = false;

  /**
   * 调用后台API标志
   */
  loading = false;

  /**
   * 分页参数初始化
   */
  queryOptions: QueryOptions = {
    page: 0,
    size: 20,
    sort: 'id,asc',
  };

  /**
   * 学生其他信息
   */
  studentDetail: StudentDetailDTO = {
    id: null,
    phone: null,
    idCard: '',
    birthDate: '',
    familyName: '',
    familyPhone: null,
    politicStatus: null,
  };

  /**
   * 学生信息
   */
  student: StudentDTO = {
    id: null,
    code: '',
    name: '',
    grade: null,
    gender: null,
    isClassEvaluationAdmin: false,
    studentDetail: this.studentDetail,
    studyYears: null,
    joinTime: null,
    academyId: null,
    academyName: null,
    professionId: null,
    professionName: null,
    classId: null,
    className: null,
  };

  /**
   * 学生编码是否已存在，true为已存在
   */
  isExist: boolean;
  /**
   * 新建学生的默认密码
   */
  defualtPW = null;
  /**
   * 是否已选择专业
   */
  hasProfession = false;
  /**
   * 校验学生编码
   */
  codeAsyncValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      this.studentService.checkoutCodeIsExist(control.value !== '' ? control.value : ' ').subscribe(data => {
        this.isExist = data.data;
      });
      setTimeout(() => {
        if (this.isExist) {
          observer.next({ error: true, duplicated: true });
        } else if (control.value.includes(' ')) {
          observer.next({ error: true, blank: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 1000);
    });

  codeChange($event) {
    // this.studentService.checkoutCodeIsExist($event !== '' ? $event : ' ').subscribe(data => {
    //   this.isExist = data.data;
    // });
  }
  /**
   * 修改窗口状态
   */
  handleCancel() {
    this.isVisible = false;
    FormUtil.resetForm(this.myForm.form);
  }

  /**
   * 修改或新增学生信息
   * @param isPreView 是否预览
   * @param item 学生信息
   */
  edit(isPreView: boolean, item: StudentDTO) {
    this.isPreView = isPreView;

    this.student = this.initStudent(item);
    this.isVisible = true;
  }

  /**
   * 初始化学生
   */
  initStudent(item: StudentDTO): StudentDTO {
    return {
      id: item ? item.id : null,
      name: item ? item.name : '',
      code: item ? item.code : '',
      grade: item ? item.grade : null,
      gender: item ? item.gender : null,
      isClassEvaluationAdmin: item ? item.isClassEvaluationAdmin : false,
      studentDetail: item ? item.studentDetail : this.studentDetail,
      studyYears: item ? item.studyYears : 1,
      joinTime: item ? item.joinTime : null,
      academyId: item ? item.academyId : null,
      academyName: item ? item.academyName : null,
      professionId: item ? item.professionId : null,
      professionName: item ? item.professionName : null,
      classId: item ? item.classId : null,
      className: item ? item.className : null,
    };
  }

  /**
   * 保存前验证数据
   */
  beforeSave() {
    if (!this.student.academyId) {
      this.msg.error('所属学院必选');
      return false;
    }
    if (!this.student.professionId) {
      this.msg.error('所属专业必选');
      return false;
    }
    if (!this.student.classId) {
      this.msg.error('所属班级必选');
      return false;
    }
    if (this.student.code === '') {
      this.msg.error('学生学号必填');
      return false;
    }
    if (this.student.grade === '') {
      this.msg.error('学生所属年级年份必填');
      return false;
    } else {
      this.student.grade = format(this.student.grade, 'YYYY');
    }
    if (this.student.name === '') {
      this.msg.error('学生名称必填');
      return false;
    }
    if (this.student.studentDetail.birthDate !== '') {
      this.student.studentDetail.birthDate = format(this.student.studentDetail.birthDate, 'YYYY-MM-DD');
    }
    if (this.student.joinTime !== '') {
      this.student.joinTime = format(this.student.joinTime, 'YYYY-MM-DD');
    }
    return true;
  }

  /**
   * 保存
   */
  save() {
    if (!this.beforeSave()) {
      return;
    }
    this.loading = true;
    if (!this.student.id) {
      // id为空，为新建
      this.studentService.create(this.student).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('保存失败，请重试'),
        () => this.afterCallCompleted(),
      );
    } else {
      // id不为空，为修改
      this.studentService.complete(this.student.id, this.student).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('修改失败，请重试'),
        () => this.afterCallCompleted(),
      );
    }
  }

  /**
   * 数据保存后的通用操作
   *
   * @param data 保存的数据
   * @param operation 操作类型
   */
  private afterItemSaved(data: StudentDTO, operation: OperationType): void {
    this.loading = false;
    this.handleCancel();
    this.notification.emit({
      operation,
      data,
    });
    this.msg.success('保存成功!');
  }

  /**
   * API调用完成后的操作
   */
  private afterCallCompleted(): void {
    this.loading = false;
  }
  ngOnInit() {
    // 获取新建学生的默认密码
    this.configurationService.findById('5').subscribe(data => {
      this.defualtPW = data.value;
    });
  }
}
